#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import threading


class OsChinaResponse(object):
    def __init__(self, status=True, error=None, data=None):
        self.code = None
        self.status = status
        self.error = error
        self.data = data

    @property
    def dict(self):
        return self.__dict__


class OsChina(object):
    """
    码云相关代码
    """

    @classmethod
    def load_project_members(cls, org, role='all'):
        """
        加载成员项目
        :return:
        """
        response = OsChinaResponse()
        member_response = cls.load_members(org, role)
        if not member_response.status:
            return member_response

        project_response = cls.load_projects(org)
        if not project_response.status:
            return project_response

        for item in project_response.data:

            repo_name, username, real_name = item.get('path'), item.get('project_creator'), item.get('description')
            info = member_response.data.get(username)
            if not info:
                continue
            info['repo_name'].append(repo_name)
            info['real_name'] = real_name
        response.data = member_response.data
        return response

    @staticmethod
    def load_members(org, role):
        """
        加载成员
        :param org:
        :param role: all/admin/member
        :return:
        """
        response = OsChinaResponse()
        try:
            data_list = []
            page = 1
            while True:
                result = requests.get(
                    url='https://gitee.com/api/v5/orgs/{org}/members'.format(org=org),
                    data={
                        'org': org,
                        'page': page,
                        'per_page': 100,
                        'role': role
                    }
                )
                members = result.json()
                data_list.extend(members)
                if len(members) < 100:
                    break
                page += 1
            response.data = {item['login']: {'username': item['login'], 'nick_name': item['name'], 'repo_name': []} for
                             item
                             in data_list}
        except Exception as e:
            response.status = False
            response.error = '获取成员失败'
        return response

    @staticmethod
    def load_projects(org):
        """
        加载项目
        :return:
        """
        response = OsChinaResponse(data=[])
        try:
            page = 1
            while True:
                result = requests.get(
                    url='https://gitee.com/api/v5/orgs/{org}/repos'.format(org=org),
                    data={
                        'org': org,
                        'page': page,
                        'per_page': 100,
                        'role': 'all'
                    }
                )
                members = result.json()
                response.data.extend(members)
                if len(members) < 100:
                    break
                page += 1
        except Exception as e:
            response.status = False
            response.error = '获取组织项目失败'
        return response

    @staticmethod
    def load_issues(org, repo, labels):
        """
        加载作业
        :param org: 组织
        :param repo: 项目（教学计划）
        :param labels: 标签，多个标签用逗号分隔，如：如: bug,performance
        :return:
        """
        response = OsChinaResponse(data=[])
        try:
            page = 1
            while True:
                result = requests.get(
                    url='https://gitee.com/api/v5/repos/{owner}/{repo}/issues'.format(owner=org,
                                                                                      repo=repo),
                    data={
                        'owner': org,
                        'repo': repo,
                        'sort': 'created',
                        'direction': 'desc',
                        'state': 'all',
                        'per_page': 100,
                        'page': page,
                        'labels': labels,
                    }
                )
                members = result.json()
                response.data.extend(members)
                if len(members) < 100:
                    break
                page += 1
        except Exception as e:
            response.status = False
            response.error = '获取issues失败'
        return response

    @staticmethod
    def load_comments(org, repo, number):
        """
        加载评论
        :param org:
        :param repo:
        :param number:
        :return:
        """
        response = OsChinaResponse(data=[])
        try:
            page = 1
            while True:
                result = requests.get(
                    url='https://gitee.com/api/v5/repos/{owner}/{repo}/issues/{number}/comments'.format(
                        owner=org,
                        repo=repo, number=number),
                    data={
                        'owner': org,
                        'repo': repo,
                        'direction': 'desc',
                        'per_page': 100,
                        'page': page,
                    }
                )
                print(result.json())
                members = result.json()
                response.data.extend(members)
                if len(members) < 100:
                    break
                page += 1
        except Exception as e:
            response.status = False
            response.error = '获取评论失败'

        return response
